<template>
    <div>
        <!-- 筛选区域 -->
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
            <h2 class="text-xl font-semibold">单品数据统计</h2>
            <div class="flex flex-col md:flex-row gap-4 w-full md:w-auto">
                <el-select v-model="selectedProduct" filterable placeholder="选择商品" class="flex-1 min-w-[200px]"
                    @change="fetchProductData">
                    <el-option v-for="product in productOptions" :key="product.id" :label="product.name"
                        :value="product.id" />
                </el-select>

                <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" :shortcuts="dateShortcuts" @change="fetchProductData" />
            </div>
        </div>

        <!-- 数据卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <el-card shadow="hover" class="bg-blue-50">
                <div class="p-4">
                    <div class="text-gray-500 text-sm mb-2">总下载量</div>
                    <div class="text-2xl font-bold text-blue-600">{{ formatNumber(productStats.totalDownloads) }}</div>
                    <div class="text-xs text-gray-400 mt-1">较上期 <span
                            :class="productStats.downloadTrend >= 0 ? 'text-green-500' : 'text-red-500'">
                            {{ productStats.downloadTrend >= 0 ? '↑' : '↓' }} {{ Math.abs(productStats.downloadTrend)
                            }}%
                        </span></div>
                </div>
            </el-card>

            <el-card shadow="hover" class="bg-purple-50">
                <div class="p-4">
                    <div class="text-gray-500 text-sm mb-2">总收藏量</div>
                    <div class="text-2xl font-bold text-purple-600">{{ formatNumber(productStats.totalFavorites) }}
                    </div>
                    <div class="text-xs text-gray-400 mt-1">较上期 <span
                            :class="productStats.favoriteTrend >= 0 ? 'text-green-500' : 'text-red-500'">
                            {{ productStats.favoriteTrend >= 0 ? '↑' : '↓' }} {{ Math.abs(productStats.favoriteTrend)
                            }}%
                        </span></div>
                </div>
            </el-card>

            <el-card shadow="hover" class="bg-green-50">
                <div class="p-4">
                    <div class="text-gray-500 text-sm mb-2">转化率</div>
                    <div class="text-2xl font-bold text-green-600">{{ productStats.conversionRate }}%</div>
                    <div class="text-xs text-gray-400 mt-1">较上期 <span
                            :class="productStats.conversionTrend >= 0 ? 'text-green-500' : 'text-red-500'">
                            {{ productStats.conversionTrend >= 0 ? '↑' : '↓' }} {{
                                Math.abs(productStats.conversionTrend) }}%
                        </span></div>
                </div>
            </el-card>
        </div>

        <!-- 图表区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <el-card shadow="hover">
                <div class="p-4">
                    <h3 class="text-lg font-semibold mb-4">下载量趋势</h3>
                    <div ref="downloadChart" class="h-80"></div>
                </div>
            </el-card>

            <el-card shadow="hover">
                <div class="p-4">
                    <h3 class="text-lg font-semibold mb-4">收藏量趋势</h3>
                    <div ref="favoriteChart" class="h-80"></div>
                </div>
            </el-card>
        </div>

        <!-- 数据表格 -->
        <el-card shadow="hover">
            <div class="p-4">
                <h3 class="text-lg font-semibold mb-4">每日数据</h3>
                <el-table :data="dailyData" stripe style="width: 100%">
                    <el-table-column prop="date" label="日期" width="120" />
                    <el-table-column prop="downloads" label="下载量" sortable>
                        <template #default="{ row }">
                            <span class="font-medium">{{ formatNumber(row.downloads) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="favorites" label="收藏量" sortable>
                        <template #default="{ row }">
                            <span class="font-medium">{{ formatNumber(row.favorites) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="conversion" label="转化率" sortable>
                        <template #default="{ row }">
                            {{ row.conversion }}%
                        </template>
                    </el-table-column>
                    <el-table-column label="趋势" width="120">
                        <template #default="{ row }">
                            <div class="flex items-center">
                                <span v-if="row.trend >= 0" class="text-green-500 flex items-center">
                                    <el-icon>
                                        <Top />
                                    </el-icon>
                                    {{ row.trend }}%
                                </span>
                                <span v-else class="text-red-500 flex items-center">
                                    <el-icon>
                                        <Bottom />
                                    </el-icon>
                                    {{ Math.abs(row.trend) }}%
                                </span>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { Top, Bottom } from '@element-plus/icons-vue'

// 图表实例
const downloadChart = ref(null)
const favoriteChart = ref(null)
let downloadChartInstance = null
let favoriteChartInstance = null

// 数据
const selectedProduct = ref('')
const dateRange = ref([getDate(-9), new Date()]) // 默认最近10天
const productOptions = ref([])
const productStats = ref({
    totalDownloads: 0,
    totalFavorites: 0,
    conversionRate: 0,
    downloadTrend: 0,
    favoriteTrend: 0,
    conversionTrend: 0
})
const dailyData = ref([])

// 日期快捷选项
const dateShortcuts = [
    {
        text: '最近7天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 6)
            return [start, end]
        }
    },
    {
        text: '最近10天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 9)
            return [start, end]
        }
    },
    {
        text: '最近30天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 29)
            return [start, end]
        }
    }
]

// 获取日期
function getDate(days) {
    const date = new Date()
    date.setDate(date.getDate() + days)
    return date
}

// 格式化日期
function formatDate(date) {
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}/${day}`
}

// 初始化图表
const initCharts = () => {
    // 销毁旧实例
    if (downloadChartInstance) downloadChartInstance.dispose()
    if (favoriteChartInstance) favoriteChartInstance.dispose()

    // 创建新实例
    downloadChartInstance = echarts.init(downloadChart.value)
    favoriteChartInstance = echarts.init(favoriteChart.value)

    // 图表数据
    const dates = dailyData.value.map(item => item.date)
    const downloads = dailyData.value.map(item => item.downloads)
    const favorites = dailyData.value.map(item => item.favorites)

    // 下载量图表配置
    const downloadOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            name: '下载量'
        },
        series: [{
            name: '下载量',
            type: 'line',
            data: downloads,
            itemStyle: {
                color: '#3b82f6'
            },
            barWidth: '60%'
        }]
    }

    // 收藏量图表配置
    const favoriteOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
                rotate: 45
            }
        },
        yAxis: {
            type: 'value',
            name: '收藏量'
        },
        series: [{
            name: '收藏量',
            type: 'line',
            data: favorites,
            itemStyle: {
                color: '#8b5cf6'
            },
            barWidth: '60%'
        }]
    }

    downloadChartInstance.setOption(downloadOption)
    favoriteChartInstance.setOption(favoriteOption)
}

// 获取商品数据
const fetchProductData = () => {
    if (!selectedProduct.value) return

    // 模拟数据 - 实际项目中替换为API调用
    const days = []
    for (let i = 9; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        days.push(formatDate(date))
    }

    // 模拟每日数据
    dailyData.value = days.map((date, index) => ({
        date,
        downloads: Math.floor(Math.random() * 200) + 50 + index * 5,
        favorites: Math.floor(Math.random() * 100) + 20 + index * 3,
        conversion: parseFloat(((Math.random() * 20 + 30)).toFixed(1)),
        trend: parseFloat(((Math.random() * 10 - 5)).toFixed(1)),
  }))

    // 计算汇总数据
    productStats.value.totalDownloads = dailyData.value.reduce((sum, item) => sum + item.downloads, 0)
    productStats.value.totalFavorites = dailyData.value.reduce((sum, item) => sum + item.favorites, 0)
    productStats.value.conversionRate = parseFloat((
        (productStats.value.totalFavorites / productStats.value.totalDownloads) * 100
    ).toFixed(1))

    // 模拟趋势数据
    productStats.value.downloadTrend = parseFloat((Math.random() * 10 - 2).toFixed(1))
    productStats.value.favoriteTrend = parseFloat((Math.random() * 8 - 1).toFixed(1))
    productStats.value.conversionTrend = parseFloat((Math.random() * 5 - 1).toFixed(1))

    // 初始化图表
    initCharts()
}

// 获取商品列表
const fetchProductOptions = () => {
    // 模拟商品数据 - 实际项目中替换为API调用
    productOptions.value = [
        { id: '1', name: '男士运动鞋-2023新款' },
        { id: '2', name: '女士高跟鞋-优雅系列' },
        { id: '3', name: '儿童帆布鞋-夏季款' },
        { id: '4', name: '户外登山靴-防水款' },
        { id: '5', name: '商务正装皮鞋-经典款' },
        { id: '6', name: '休闲乐福鞋-透气款' },
        { id: '7', name: '沙滩凉鞋-防滑底' }
    ]

    // 默认选择第一个商品
    if (productOptions.value.length > 0) {
        selectedProduct.value = productOptions.value[0].id
        fetchProductData()
    }
}

// 格式化数字
const formatNumber = (num) => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 响应式调整图表大小
const handleResize = () => {
    if (downloadChartInstance) downloadChartInstance.resize()
    if (favoriteChartInstance) favoriteChartInstance.resize()
}

onMounted(() => {
    fetchProductOptions()
    window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
    if (downloadChartInstance) downloadChartInstance.dispose()
    if (favoriteChartInstance) favoriteChartInstance.dispose()
    window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* 自定义样式 */
.el-card {
    border-radius: 0.5rem;
}

.el-table {
    border-radius: 0.5rem;
    overflow: hidden;
}
</style>